package com.atguigu.tingshu.album.task;

import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * ClassName : RebuildBloomFilterTask
 * Package : com.atguigu.tingshu.album.task
 * Description :
 * <p>
 * Author: LHZ
 * Create: 2025/7/30 16:36
 * Version: 1.0
 */
@Slf4j
@Component
public class RebuildBloomFilterTask {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private AlbumInfoService albumInfoService;


    @Scheduled(cron = "0/500 * * * * ?")
    public void rebuildBloomFilter(){
        //获取当前布隆过滤器 及布隆过滤器的配置信息: 期望数据规模 误判率 现有元素数量(预估值)
        RBloomFilter<Long> oldBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        long expectedInsertions = oldBloomFilter.getExpectedInsertions();
        double falseProbability = oldBloomFilter.getFalseProbability();
        long count = oldBloomFilter.count();
        RBloomFilter<Long> newBloomFilter;
        //判断是否满足扩容条件
        if(count >= expectedInsertions){
            log.info("满足扩容条件,开始扩容重建...");
            newBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER + ":new");
            if(!newBloomFilter.isExists()){
                //新布隆过滤器进行初始化 原有数据规模*2
                newBloomFilter.tryInit(expectedInsertions * 2, falseProbability);
            }
        }else{
            //如果不满足扩容条件
            log.info("不满足扩容条件,开始重建...");
            newBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER + ":new");
            //初始化布隆过滤器
            newBloomFilter.tryInit(expectedInsertions,falseProbability);
        }
        //将数据中现有合法专辑id存入到新布隆过滤器中
        List<AlbumInfo> albumInfoList = albumInfoService.list(
                new LambdaQueryWrapper<AlbumInfo>()
                        .eq(AlbumInfo::getStatus, SystemConstant.ALBUM_STATUS_PASS)
                        .select(AlbumInfo::getId)
        );
        if(!CollectionUtils.isEmpty(albumInfoList)){
            for (AlbumInfo albumInfo : albumInfoList) {
                newBloomFilter.add(albumInfo.getId());
            }
        }
        //删除旧的布隆过滤器
        oldBloomFilter.delete();
        //将新的布隆过滤器重命名
        newBloomFilter.rename(RedisConstant.ALBUM_BLOOM_FILTER);
        log.info("布隆过滤器重建完成...");
    }

}